package com.example.schoolblog.blog.Provider;


import com.alibaba.fastjson.JSON;
import com.example.schoolblog.blog.Dto.AccessTokenDto;
import com.example.schoolblog.blog.Dto.UserDto;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;


//将当前类初始化到Spring容器中的上下文，我们可以通过直接使用引用就可以调用相应的方法
@Component
public class GithupProvider {
    //获取githup用户的token
    public String getAccessToken(AccessTokenDto accessToken){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessToken));
        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String access_token = response.body().string().split("&")[0].split("=")[1];
            return access_token;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    //根据token获取githup用户的信息
    public UserDto getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user")
                .header("Authorization","token "+accessToken)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            UserDto userDto = JSON.parseObject(string,UserDto.class);
            return userDto;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
